package indi.zhifa.study2024.class001.busy.generalTest.business.simplecal.service.impl;

import indi.zhifa.study2024.class001.busy.generalTest.business.simplecal.entity.request.APlusBRequest;
import indi.zhifa.study2024.class001.busy.generalTest.business.simplecal.entity.request.FabRequest;
import indi.zhifa.study2024.class001.busy.generalTest.business.simplecal.entity.response.APlusBResponse;
import indi.zhifa.study2024.class001.busy.generalTest.business.simplecal.entity.response.DivideZeroErrorResponse;
import indi.zhifa.study2024.class001.busy.generalTest.business.simplecal.entity.response.FabResultResponse;
import indi.zhifa.study2024.class001.busy.generalTest.business.simplecal.service.ISimpleCalService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class SimpleCalServiceImpl implements ISimpleCalService {

    BigDecimal[] fabMemo;

    public SimpleCalServiceImpl(){
        fabMemo = new BigDecimal[65536];
        fabMemo[1] = new BigDecimal("1");
        fabMemo[2] = new BigDecimal("1");
    }


    @Override
    public APlusBResponse plus(APlusBRequest pRequest) {
        APlusBResponse aPlusBResponse = new APlusBResponse();
        aPlusBResponse.setResult(pRequest.getA()+pRequest.getB());
        return aPlusBResponse;
    }

    @Override
    public FabResultResponse fab(FabRequest request) {
        int n = request.getN();
        FabResultResponse fabResultResponse = new FabResultResponse();
        if(fabMemo[n] != null){
            fabResultResponse.setResult(fabMemo[n]);
            return fabResultResponse;
        }
        FabRequest n1Request = new FabRequest();
        n1Request.setN(n-1);
        FabRequest n2Request = new FabRequest();
        n2Request.setN(n-2);
        BigDecimal res = fab(n1Request).getResult().add(fab(n2Request).getResult());
        fabMemo[n] = res;
        fabResultResponse.setResult(res);
        return fabResultResponse;
    }

    @Override
    public DivideZeroErrorResponse divideZero() {
        DivideZeroErrorResponse res = new DivideZeroErrorResponse();
        res.setResult(35/0);
        return res;
    }
}
